<template>
  <div>
    <el-row :gutter="20">
      <transition-group name="edit">
        <el-col v-for="item in roleList" :key="item.role_id" :span="6">
          <el-card
            :body-style="bodyCardStyle"
            @mouseover.native="hoverId = item.role_id"
            @mouseleave.native="hoverId = 0"
          >
            <h5 v-text="item.role_name"></h5>

            <div class="mask" v-show="hoverId === item.role_id">
              <el-button
                type="text"
                icon="el-icon-edit-outline"
                @click="beginUpdate(item)"
                >编辑</el-button
              >

              <el-button
                type="text"
                icon="el-icon-setting"
                @click="beginRoleFuncConfig(item.role_id)"
                >功能分配</el-button
              >

              <el-button
                type="text"
                icon="el-icon-delete"
                @click="removeHandler(item.role_id)"
                >删除</el-button
              >
            </div>
          </el-card>
        </el-col>
      </transition-group>

      <el-col :span="6">
        <el-card
          :body-style="bodyCardStyle"
          style="border: 1px dashed #333"
          @click.native="beginAdd"
        >
          <i class="el-icon-plus"></i>
        </el-card>
      </el-col>
    </el-row>

    <el-dialog
      :title="`角色编辑 - ${edit.mode ? '新增' : '修改'}`"
      :visible.sync="edit.isEdit"
      width="30%"
      :modal="false"
    >
      <el-form
        label-width="100px"
        :model="edit.model"
        :rules="edit.validRules"
        status-icon
        ref="form"
      >
        <el-form-item label="角色名称" prop="role_name">
          <!--prop表示验证rules中的那个role_name-->

          <el-input v-model.trim="edit.model.role_name"></el-input>
        </el-form-item>
      </el-form>

      <template slot="footer">
        <el-button @click="save">确定</el-button>

        <el-button @click="edit.isEdit = false">取消</el-button>
      </template>
    </el-dialog>
    <el-drawer
      :show-close="false"
      :visible="edit2.isEdit"
      size="600px"
      :modal="false"
      class="custom-drawer"
    >
      <h3 slot="title">角色功能分配</h3>
      <div class="tree-wrapper">
        <el-tree
          :data="edit2.treeData"
          class="custom-tree"
          :default-expand-all="true"
          :expand-on-click-node="false"
        >
          <span
            slot-scope="{ node, data }"
            class="custom-tree-node"
            :class="{ active: data.selected }"
          >
            <span>
              <i
                v-if="data.func_key"
                class="el-icon-menu"
                style="color: rgb(64,158,255); margin-right: 10px;"
              ></i>
              <span v-text="data.func_name"></span>
            </span>
            <span
              class="switch-wrapper"
              :class="{ parent: data.func_fid === 0 }"
            >
              <el-switch
                v-model="data.selected"
                @change="switchChangeHandler(data)"
              ></el-switch>
            </span>
          </span>
        </el-tree>
        <el-button type="primary" @click="configRoleFunc">确定</el-button>
        <el-button @click="edit2.isEdit = false">取消</el-button>
      </div>
    </el-drawer>
  </div>
</template>

<script type="text/ecmascript-6">
//	import { createNamespacedHelpers } from 'vuex';
//	const { mapActions, mapState } = createNamespacedHelpers('role');           映射的已经绑定了role这个子仓库

import { mapState, mapActions } from 'vuex'; //一个组件映射多个仓库
import { RoleFuncApi } from '@/util/api.js';
export default {
	name: "Role",
	data() {
		return {
			hoverId: 0,
			bodyCardStyle: {
				display: "flex",
				justifyContent: "center",
				alignItems: "center",
				height: "80px",
			},
			edit: {
				isEdit: false, //标识是否进入编辑状态
				mode: false, //标识当前是新增还是修改，默认是新增
				model: { role_id: 0, role_name: "" },
				validRules: {
					role_name: [ //要验证的是role_name,要与model中的键名对应
						//添加的角色要唯一不能与已有的元素重复。要自定义验证   { validator: function() {},trigger: "" ,... }
						{
							validator: (rule, value, next) => {
								if (value === "") next(new Error('角色名不能为空')); //new一个Error对象提示用户。
								else if (value.length < 2 || value.length > 15) next(new Error("角色名长度为2-10个字符"));
								else if (this.roleList.some(item => item.role_name === value && item.role_id !== this.edit.model.role_id)) next(new Error("角色名已存在！"));
								else next();
							},
							trigger: "blur"
						}
						//	                                                { required: true, message: "角色名称不能为空", trigger: "blur" },
						//	                                                { min: 2, max: 10,message: "角色名称长度为2-10个字符",trigger: "blur" }
					]
				}
			},
			edit2: {
				treeData: [],
				isEdit: false,
				roleFuncIds: [],
				model: { role_id: 0, role_func_ids: "" }
			}
		};
	},
	computed: {
		...mapState('role', { roleList: "list" }),
		...mapState('func', { funcList: "funcList" }),
	},
	methods: {
		...mapActions('role', { roleInit: "init", roleRemove: "remove", roleAdd: "add", roleUpdate: "update" }),
		...mapActions('func', { funcInit: "funcInit" }),
		//角色管理
		async removeHandler(id) {
			await this.$confirmEx('您确认要删除么？', '提示', { type: "warning" });
			await this.roleRemove({ payload: id });
			this.$message({ type: "success", message: "角色删除成功" });
			//				this.$confirm('您确认要删除么？','提示', {type: "warning"})
			//					.then(async () => {
			//					        await this.roleRemove({ payload: id });
			//				                this.$message({type: "success",message: "角色删除成功"});
			//					})
			//					.catch(() => {});
		},
		beginAdd() {
			if (this.$refs.form) this.$refs.form.resetFields();
			this.edit.model.role_id = 0;
			this.edit.model.role_name = '';
			this.edit.mode = true;
			this.edit.isEdit = true;
		},
		beginUpdate(role) {
			if (this.$refs.form) this.$refs.form.resetFields();
			this.edit.model.role_id = role.role_id;
			this.edit.model.role_name = role.role_name;
			this.edit.mode = false;
			this.edit.isEdit = true;
		},
		save() {
			//要验证表单
			this.$refs.form.validate() //验证整个表单，会返回promise对象
				.then(async () => {
					//再判断是新增还是修改
					if (this.edit.mode) { //新增
						await this.roleAdd({ payload: JSON.parse(JSON.stringify(this.edit.model)) });
						this.$message({
							type: "success",
							message: "角色添加成功！"
						});
					} else { //修改
						await this.roleUpdate({ payload: JSON.parse(JSON.stringify(this.edit.model)) });
						this.$message({
							type: "success",
							message: "角色修改成功！"
						});
					}
					this.edit.isEdit = false;
				})
				.catch(() => {});
		},
		//角色功能分配
		async beginRoleFuncConfig(role_id) {
			this.edit2.model.role_id = role_id;
			const list = await RoleFuncApi.getRoleFuncs(role_id);
			const roleFuncIds = [];
			list.forEach(func => roleFuncIds.push(func.func_id));

			let result = [];
			this.funcList.filter(func => func.func_fid === 0).forEach((item) => {
				let node = JSON.parse(JSON.stringify(item));
				node.selected = roleFuncIds.some(func => func === item.func_id);
				if (!node.func_key) {
					let children = this.funcList.filter(func => func.func_fid === node.func_id);
					if (children.length) {
						node.children = [];
						children.forEach(item2 => {
							let child = JSON.parse(JSON.stringify(item2));
							child.selected = roleFuncIds.some(func => func === item2.func_id);
							node.children.push(child);
						});
					}
				}
				result.push(node);
			});
			this.edit2.treeData = result;
			this.edit2.isEdit = true;
		},
		switchChangeHandler(func) {
			if (func.children) {
				func.children.forEach(item => item.selected = func.selected);
			} else {
				if (func.func_fid !== 0) {
					let father = this.edit2.treeData.find(item => item.func_id === func.func_fid);
					father.selected = father.children.some(item => item.selected);
				}
			}
		},
		async configRoleFunc() {
			let ids = [];
			this.edit2.treeData.forEach(item => {
				if (item.selected) {
					ids.push(item.func_id);
					if (item.children) {
						item.children.forEach(item2 => {
							if (item2.selected) ids.push(item2.func_id);
						});
					}
				}
			});
			this.edit2.model.role_func_ids = ids.join(',');
			await RoleFuncApi.configRoleFunc(this.edit2.model);
			this.edit2.isEdit = false;
			this.$message({ type: "success", message: "角色功能配置成功！" });
		}
	},
	async created() {
		await this.roleInit(); //通知role仓库初始化所有角色数据
		await this.funcInit(); //通知func仓库初始化所有功能数据
	}
};
</script>

<style lang="stylus" type="text/stylus" scoped>
.el-drawer
	padding 20px!important
	.tree-wrapper
		padding 20px
		.el-tree
			width 500px
			.custom-tree-node
				width 100%
				display flex
				justify-content space-between
				align-items center
				font-size 16px
				color #aaa
				&.active
					color #000
				span.switch-wrapper
					margin-right 50px
					&.parent
						transform translateX(100%)
/*transition-group 动画*/
.edit-enter,.edit-leave-to
	opacity 0
.edit-enter-active,.edit-leave-active
	transition all 0.6s
.el-card
	position relative
	margin-bottom 20px
	h5
		font-size 20px
		color #bf1111
	.mask
		position absolute
		left 0
		top 0
		right 0
		bottom 0
		background-color rgba(0,0,0,.3)
		display flex
		justify-content center
		align-items center
		.el-button
			color #409eff
			cursor pointer
			&:hover
				text-decoration underline
				color #fff
</style>
